package com.bailiban.user.filter;

import com.bailiban.common.entity.Result;
import com.bailiban.common.entity.StatusCode;
import com.bailiban.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhulang
 * @Classname JwtFilter
 * @Description JwtFilter
 */
@Component
public class JwtFilter extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 前置拦截器
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器中");
        String authorization = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(authorization) && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            Claims claims = jwtUtil.parseJWT(token);
            if (claims != null && "admin".equals(claims.get("roles"))) {
                //用于admin角色
                request.setAttribute("claims_roles", claims);
            } else if (claims != null && "user".equals(claims.get("roles"))) {
                //用于user角色
                request.setAttribute("claims_roles", claims);
            }
        }
        return true;
    }
}
